//
//  LXExtension+NSArray.swift
//  LXExtensions
//
//  Created by yoctech on 2021/10/8.
//

import Foundation

@objc public extension NSArray {
    
    /// 数组转json字符串
    @objc func lx_toJson() -> String {
        if (!JSONSerialization.isValidJSONObject(self)) {
            return ""
        }
        guard let data = try? JSONSerialization.data(withJSONObject: self, options: []) else {
            return ""
        }
        guard let str = String.init(data: data, encoding: String.Encoding.utf8) else {
            return ""
        }
        return str.replacingOccurrences(of: "\\/", with: "/")
    }
    
    /// 从json文件里面读取数组
    /// - Parameter fileName: json文件名,不包含.json后缀
    /// - Returns: 结果数组,如果读取失败则返回空数组
    @objc static func lx_fromJsonFile(_ fileName :String) -> NSArray {
        var path: String
        if fileName.contains("/") {
            path = fileName
        }else{
            path = Bundle.main.path(forResource: fileName, ofType: "json") ?? ""
        }
        if path.isEmpty {
            return []
        }
        let filePath = URL(fileURLWithPath: path)
        do {
            let data = try Data.init(contentsOf: filePath)
            let jsonData: Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
            let jsonArr = jsonData as! NSArray
            return jsonArr
        } catch _ {
            return []
        }
    }
    
    /// 去除数组重复元素
    /// - Returns: 去除数组重复元素后的数组
    @objc func lx_removeDuplicate() -> NSArray {
        return NSSet(array: self as! [Any]).allObjects as NSArray
    }
}
